<template>
  <div class="afterSaleRecord">
    <ContentWrap style="padding-top:5px">
      <FormContainer :column="5">
        <el-form
          ref="formOrder"
          :model="formData"
          label-width="110px"
        >
          <el-form-item prop="officeCode" label="办事处">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/office/ref/page"
              placeholder="请选择"
              lable-name="name"
              value-name="code"
              method="get"
              :value.sync="formData.officeCode"
              :lable.sync="formData.officeName"
              @selectChange="officeSelectChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="disCode" label="经销商">
            <!-- 未完结前可修改 -->
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/dealer/ref/page"
              method="get"
              placeholder="请选择经销商"
              :params="{query:{officeCode:formData.officeCode},type:0}"
              lable-name="name"
              value-name="code"
              custom-name="codeOrName"
              :parent-id="formData.officeCode"
              :value.sync="formData.disCode"
              :lable.sync="formData.disName"
              :current-id.sync="formData.disId"
              clearable
              @selectChange="disSelectChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="workOrderCode" label="工单编号">
            <el-input v-model="formData.workOrderCode" clearable placeholder="工单编号" />
          </el-form-item>
          <el-form-item
            prop="appraiseTime"
            label="评价时间"
            :span="24 / 5 * 2"
          >
            <el-date-picker
              v-model="formData.appraiseTime"
              type="datetimerange"
              clearable
              opt
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              @focus="handleDateTimeRageFocus('appraiseTime')"
            />
          </el-form-item>
          <el-form-item prop="serviceSatisfaction" label="服务满意度" hidden>
            <el-select v-model="formData.serviceSatisfaction" multiple clearable>
              <el-option value="5" label="满意" />
              <el-option value="9" label="一般" />
              <el-option value="1" label="不满意" />
            </el-select>
          </el-form-item>
          <el-form-item prop="serviceAttitude" label="服务态度">
            <el-select v-model="formData.serviceAttitude" multiple clearable>
              <el-option value="5" label="满意" />
              <el-option value="9" label="一般" />
              <el-option value="1" label="不满意" />
            </el-select>
          </el-form-item>
          <el-form-item prop="processingSpeed" label="处理速度">
            <el-select v-model="formData.processingSpeed" multiple clearable>
              <el-option value="5" label="满意" />
              <el-option value="9" label="一般" />
              <el-option value="1" label="不满意" />
            </el-select>
          </el-form-item>
          <el-form-item prop="returnVisitState" label="回访状态">
            <el-select v-model="formData.returnVisitState" clearable>
              <el-option value="0" label="待回访" />
              <el-option value="1" label="已完成" />
            </el-select>
          </el-form-item>

          <el-form-item prop="handlerGroupNo" label="处理业务组">
            <SearchSelectPicker
              url="/call-center/api/v1/businessGroup/page"
              placeholder="请选择"
              lable-name="groupName"
              value-name="groupNo"
              method="post"
              :value.sync="formData.handlerGroupNo"
              :lable.sync="formData.handlerGroupName"
              @selectChange="groupNoSelectChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="handler" label="处理人">
            <SearchSelectPicker
              url="/call-center/api/v1/staffInfo/page"
              placeholder="请选择"
              :params="{query:{groupNo:formData.handlerGroupNo},type:0}"
              lable-name="staffName"
              value-name="accountNo"
              method="post"
              :value.sync="formData.handler"
              :lable.sync="formData.handlerName"
              @selectChange="staffSelectChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item align="right" label-width="0px" show more style="white-space: nowrap;">
            <Button @click="resetSearch('formOrder')">重置</Button>
            <Button type="primary" enter @click="querySearch('formOrder')">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="button-container" style="justify-content:flex-start;padding-top:10px">
        <Button type="primary" @click="handleReturnVisit">回访</Button>
      </div>
      <table-box
        ref="refTable"
        table-size="small"
        :table-config="tableConfig"
        :other-filters="otherFilters"
        :off-set="-50"
        show-index
        :show-selection="true"
        :show-custom-setting="false"
        :selected-arry.sync="tableSelected"
        @selection-change="handleselectionChange"
        @row-click="handleRowClick"
      />
    </ContentWrap>
    <el-image-viewer
      v-if="showViewer"
      :on-close="closeViewer"
      :url-list="urlList"
      style="z-index:9999"
    />
  </div>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import ContentWrap from '@/components/ContentWrap'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import Button from '@/components/Button'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import { getOfficeDetail, getBusinessGroup } from '@/api/mscInfo'
import { putReturnVisit } from '@/api/workOrderEvaluation'
import { parseTime } from '@/utils/'
export default {
  name: 'WorkOrderEvaluation',
  components: {
    FormContainer,
    ContentWrap,
    SearchSelectPicker,
    Button,
    ElImageViewer
  },
  data() {
    const that = this
    return {
      showViewer: false,
      urlList: [],
      activeRowData: '',
      formData: {
        officeCode: '',
        officeName: '',
        disCode: '',
        disName: '',
        workOrderCode: '',
        appraiseTime: '',
        serviceSatisfaction: '',
        serviceAttitude: '',
        processingSpeed: '',
        returnVisitState: '',
        handlerGroupNo: '',
        handler: ''
      },
      otherFilters: [], // 表格额外查询条件
      otherRaws: {},
      tableSelected: [], // 选择列
      tableConfig: {
        interfacePath: `/call-center/api/v1/workOrderAppraise/page`,
        tabIndex: 0,
        hideFuncBar: true,
        // sort: 'createTime',
        // order: 'desc',
        setting: [
          {
            prop: 'memberCardNumber',
            label: '会员卡号',
            minWidth: 150
          },
          {
            prop: 'workOrderCode',
            label: '工单编号',
            minWidth: 150,
            className: 'btn-green',
            isButton: true,
            clickFun: this.toDetail // workOrderId
          },
          {
            prop: 'officeName',
            label: '办事处',
            minWidth: 150
          },
          {
            prop: 'disName',
            label: '经销商',
            minWidth: 150
          },
          {
            prop: 'handlerName',
            label: '工单处理人',
            minWidth: 150
          },
          {
            prop: 'appraiseTime',
            label: '评价时间',
            minWidth: 150,
            formatData: ({ appraiseTime }) => {
              return parseTime(appraiseTime, '{y}-{m}-{d} {h}:{i}:{s}')
            }
          },

          {
            prop: 'serviceSatisfaction',
            label: '服务满意度',
            minWidth: 150
          },
          {
            prop: 'serviceAttitude',
            label: '服务态度',
            minWidth: 150
          },
          {
            prop: 'processingSpeed',
            label: '处理速度',
            minWidth: 150
          },
          {
            prop: 'appraiseContent',
            label: '评价内容',
            minWidth: 150
          },
          {
            prop: 'returnVisitState',
            label: '回访状态',
            minWidth: 150,
            render: (creat, row) => {
              if (row.returnVisitState) {
                return <span>已完成</span>
              } else {
                return <span>待回访</span>
              }
            }
          },
          {
            label: '图片',
            render: (creat, row) => {
              if (row.annexList && row.annexList.length) {
                return <span class='btn-green' onClick={that.onPreview.bind(this, row)}>查看</span>
              } else {
                return ''
              }
            }
            // button: [
            //   {
            //     name: '查看',
            //     clickFun: this.onPreview,
            //     className: 'btn-green',
            //     type: 'text'
            //   }
            // ]
          }
        ]
      }
    }
  },
  mounted() {
  },
  methods: {
    handleDateTimeRageFocus(filed) {
      const val = this.formData[filed]
      if (!val || val.length === 0) {
        const today = parseTime(new Date(), '{y}-{m}-{d}')
        const defautVal = [`${today} 00:00:00`, `${today} 21:00:00`]
        this.$set(this.formData, filed, defautVal)
      }
    },
    // 日期加1
    addDay(datetime, days) {
      const old_time = new Date(datetime.replace(/-/g, '/'))
      const fd = new Date(old_time.valueOf() + days * 24 * 60 * 60 * 1000)
      let new_time = fd.getFullYear() + '-'
      const month = fd.getMonth() + 1
      if (month >= 10) {
        new_time += month + '-'
      } else {
        // 在小于10的月份上补0
        new_time += '0' + month + '-'
      }
      if (fd.getDate() >= 10) {
        new_time += fd.getDate()
      } else {
        // 在小于10的日期上补0
        new_time += '0' + fd.getDate()
      }
      return new_time
    },
    // 获取经销商对应的办事处
    findOfficeInfo(disCode) {
      getOfficeDetail(disCode, { hiddenError: true }).then(res => {
        if (res.success === 1) {
          this.formData.officeName = res.data.name
          this.formData.officeCode = res.data.code
        }
      })
    },
    // 办事处值改变时
    officeSelectChange(data) {
      setTimeout(() => { this.$refs['formOrder'].validateField(['officeCode']) }, 0)
      this.resetOfficeName()
    },
    // 经销商值改变时
    disSelectChange(data) {
      setTimeout(() => { this.$refs['formOrder'].validateField(['disCode']) }, 0)
      // this.resetDisName()
      // if (!this.formData.officeCode && data.code) this.findOfficeInfo(data.code)
      // if (data && data.name) this.checkShopNum(data.name)
    },
    // 业务组值改变时
    groupNoSelectChange(data) {
      setTimeout(() => { this.$refs['formOrder'].validateField(['handlerGroupNo']) }, 0)
      this.resetgroupName()
    },
    // 坐席值改变时
    staffSelectChange(data) {
      setTimeout(() => { this.$refs['formOrder'].validateField(['handler']) }, 0)
      // this.resetDisName()
      if (!this.formData.handlerGroupNo && data && data.accountNo) this.findGroupInfo(data.accountNo)
    },
    findGroupInfo(data) {
      getBusinessGroup(data).then(res => {
        if (res.success === 1) {
          console.log('res', res.data)
          this.formData.handlerGroupName = res.data[0].groupName
          this.formData.handlerGroupNo = res.data[0].groupNo
        }
      })
    },
    resetgroupName() {
      this.$set(this.formData, 'handler', '')
      // this.$set(this.formData, 'disName', '')
    },
    /**
     * 重置办事处以下信息
     */
    resetOfficeName() {
      // const _this = this
      // this.$set(this.formData, 'officeCode', '')
      // this.$set(this.formData, 'officeName', '')
      this.$set(this.formData, 'disCode', '')
      this.$set(this.formData, 'disName', '')
    },
    /**
     * 查询表单
     */
    querySearch(formName, onPage) {
      const filtersRaw = []
      if (this.formData.officeCode && this.formData.officeCode.length) {
        filtersRaw.push({
          'id': 'officeCode',
          'property': 'officeCode',
          'operator': '=',
          'value': this.formData.officeCode
        })
      }
      if (this.formData.disCode && this.formData.disCode.length) {
        filtersRaw.push({
          'id': 'disCode',
          'property': 'disCode',
          'operator': '=',
          'value': this.formData.disCode
        })
      }
      if (this.formData.workOrderCode && this.formData.workOrderCode.length) {
        filtersRaw.push({
          'id': 'workOrderCode',
          'property': 'workOrderCode',
          'operator': 'like',
          'value': this.formData.workOrderCode
        })
      }
      if (this.formData.appraiseTime && this.formData.appraiseTime.length) {
        filtersRaw.push({
          'id': 'appraiseTime1',
          'property': 'appraiseTime',
          'operator': '>=',
          'value': this.formData.appraiseTime[0]
        })
        filtersRaw.push({
          'id': 'appraiseTime2',
          'property': 'appraiseTime',
          'operator': '<=',
          'value': this.formData.appraiseTime[1]
        })
      }
      if (this.formData.serviceSatisfaction && this.formData.serviceSatisfaction.length) {
        const numList = this.formData.serviceSatisfaction.map(item => Number(item))
        if (this.formData.serviceSatisfaction.includes('9')) {
          const numIndex = numList.findIndex(item => item === 9)
          numList.splice(numIndex, 1)
          const valueList = [...numList, ...[2, 3, 4]]
          filtersRaw.push({
            'id': 'serviceSatisfaction',
            'property': 'serviceSatisfaction',
            'operator': 'in',
            'value': `[${valueList.join(',')}]`
          })
        } else {
          filtersRaw.push({
            'id': 'serviceSatisfaction',
            'property': 'serviceSatisfaction',
            'operator': 'in',
            'value': `[${numList.join(',')}]`
          })
        }
      }
      if (this.formData.serviceAttitude && this.formData.serviceAttitude.length) {
        const numList = this.formData.serviceAttitude.map(item => Number(item))
        if (this.formData.serviceAttitude.includes('9')) {
          const numIndex = numList.findIndex(item => item === 9)
          numList.splice(numIndex, 1)
          const valueList = [...numList, ...[2, 3, 4]]
          filtersRaw.push({
            'id': 'serviceAttitude',
            'property': 'serviceAttitude',
            'operator': 'in',
            'value': `[${valueList.join(',')}]`
          })
        } else {
          filtersRaw.push({
            'id': 'serviceAttitude',
            'property': 'serviceAttitude',
            'operator': 'in',
            'value': `[${numList.join(',')}]`
          })
        }
      }
      if (this.formData.processingSpeed && this.formData.processingSpeed.length) {
        const numList = this.formData.processingSpeed.map(item => Number(item))
        if (this.formData.processingSpeed.includes('9')) {
          const numIndex = numList.findIndex(item => item === 9)
          numList.splice(numIndex, 1)
          const valueList = [...numList, ...[2, 3, 4]]
          filtersRaw.push({
            'id': 'processingSpeed',
            'property': 'processingSpeed',
            'operator': 'in',
            'value': `[${valueList.join(',')}]`
          })
        } else {
          filtersRaw.push({
            'id': 'processingSpeed',
            'property': 'processingSpeed',
            'operator': 'in',
            'value': `[${numList.join(',')}]`
          })
        }
      }
      if (this.formData.returnVisitState && this.formData.returnVisitState.length) {
        filtersRaw.push({
          'id': 'returnVisitState',
          'property': 'returnVisitState',
          'operator': '=',
          'value': this.formData.returnVisitState
        })
      }
      if (this.formData.handlerGroupNo && this.formData.handlerGroupNo.length) {
        filtersRaw.push({
          'id': 'handlerGroupNo',
          'property': 'handlerGroupNo',
          'operator': '=',
          'value': this.formData.handlerGroupNo
        })
      }
      if (this.formData.handler && this.formData.handler.length) {
        filtersRaw.push({
          'id': 'handler',
          'property': 'handler',
          'operator': '=',
          'value': this.formData.handler
        })
      }
      this.otherFilters = [...filtersRaw]
      this.refreshTable(onPage)
      // }
      // })
    },
    resetSearch() {
      // const index1 = this.searchConfig.findIndex(v => v.prop === 'handler')
      // this.$set(this.searchConfig[index1].dialogConfig, 'filtersRaw', [])
      // const index2 = this.searchConfig.findIndex(v => v.prop === 'disCode')
      // this.$set(this.searchConfig[index2].dialogConfig, 'filtersRaw', [])
      const obj = {
        officeCode: '',
        officeName: '',
        disCode: '',
        disName: '',
        workOrderCode: '',
        appraiseTime: '',
        serviceSatisfaction: '',
        serviceAttitude: '',
        processingSpeed: '',
        returnVisitState: '',
        handlerGroupNo: '',
        handler: ''
      }
      this.$set(this, 'formData', obj)
    },
    handleRowClick({ row }) {
      this.$refs.refTable.clearSelection()
      this.$nextTick(() => {
        this.$refs.refTable.toggleRowSelection(row, true)
        this.activeRowData = row || ''
      })
    },
    handleselectionChange(val) {
      this.tableSelected = val
    },
    // 回访
    handleReturnVisit() {
      if (!this.singleJudge(this.tableSelected, '回访', false)) {
        return
      }
      const tmpArr = this.tableSelected.filter(row => row.returnVisitState === 1)
      if (tmpArr.length > 0) {
        this.$message.warning(`当前所选数据为已完成状态，请勿重复操作`)
        return
      }
      this.$confirm(`此操作将当前所选数据回访完成,是否继续`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = this.tableSelected.map(item => item.id)
        putReturnVisit(data).then(res => {
          if (res.success) {
            this.$message.success('操作成功')
            this.$nextTick(() => {
              this.$refs.refTable.initTableData('onPage')
              this.activeRowData = ''
              this.tableSelected = []
            })
          }
        })
      })
      // putReturnVisit(data).then(res => {})
    },
    // 查看详情
    toDetail(row) {
      this.$router.push({ name: 'DisposeOrderDetails', query: { id: row.workOrderId }})
    },
    // 打开图片查看器
    onPreview(row) {
      const s = process.env.VUE_APP_BASE_QUP
      const urlArr = row.annexList.map(item => {
        const url = s + item.filePath
        return url
      })
      this.urlList = urlArr
      this.showViewer = true
    },
    // 关闭查看器
    closeViewer() {
      this.showViewer = false
      this.urlList = []
    },
    // 刷新主表
    refreshTable(isInit) {
      this.$nextTick(() => {
        this.$refs.refTable && this.$refs.refTable.initTableData(isInit ? '' : 'onPage')
        this.activeRowData = ''
        this.tableSelected = []
      })
    }
  }
}
</script>
<style lang='scss'>
.btn-green{
  color: $qup-color-primary !important;
  cursor: pointer;
}
</style>
